import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.totalvalidator.sgml.RealAttribute;
import com.totalvalidator.sgml.Tag;


public class InputExtractor implements Extractor {

	public boolean extract(List<Tag> tags, String extractor) {
		boolean result = false;
		String multi = "false";
		String element = "input";
		String key = "name";
		String value="value";
		String attributes = "";
		Hashtable<String, String> attrs = new Hashtable<String, String>();
		java.util.StringTokenizer tokens = new java.util.StringTokenizer(extractor,";=");
		while(tokens.hasMoreElements()){
			String token = tokens.nextToken();
            if(token.equalsIgnoreCase("condition")){
				attributes = tokens.nextToken();
			}
		}
		if(attributes.length()>0){
			tokens = new java.util.StringTokenizer(attributes,"{},");
			while(tokens.hasMoreElements()){
				attrs.put(tokens.nextToken(), tokens.nextToken());
			}
		}

		
		for(int i=0; i< tags.size(); i++){
			Tag tag = (Tag)tags.get(i);
			Map map = tag.getAttributes();
			boolean isfind = false;
			if(element.equalsIgnoreCase(tag.getElement(false))){
				isfind = true;
				java.util.Enumeration en = attrs.keys();
				while(en.hasMoreElements()){
					String k = (String)en.nextElement();
					String v = attrs.get(k);
					Object obj = map.get(k);
					if(obj==null){
						isfind = false;
						break;
					}
					if(RealAttribute.class.isInstance(obj)){
						RealAttribute realAttr = (RealAttribute)obj;
						if(!realAttr.getValue().equalsIgnoreCase(v)){
							isfind = false;
							break;
						}
					}
				}
			}
			if(isfind){
				
				Object obj = map.get(key);
				if(RealAttribute.class.isInstance(obj)){
					RealAttribute realAttr = (RealAttribute)obj;
					key = realAttr.getValue();
				}	
				obj = map.get(value);
				if(RealAttribute.class.isInstance(obj)){
					RealAttribute realAttr = (RealAttribute)obj;
					value = realAttr.getValue();
				}	
				PlayData.addSessionData(key, value);
				System.out.println("extract data:"+key+","+value);
				result = true;
				if(multi.equalsIgnoreCase("false")){
					return true;
				}
			}
		}
		return result;
	}

}
